/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
 
package org.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import org.demo.util.bean.ExaHttpDownConfig;

/**
 * http文件下载工具
 * 
 * @author jx-air
 * @date 2018年2月24日 上午10:10:55
 * @version 1.0
 */
public class ExaHttpDownUtil {
	
	public static void main(String[] args) {
		//设置配置
		ExaHttpDownConfig exaHttpDownConfig = new ExaHttpDownConfig();
//		exaHttpDownConfig.setReadTimeout(readTimeout);
		exaHttpDownConfig.setProxy("127.0.0.1", 8888);
		
		exaHttpDownConfig.addRequestPro("", "")
			.addRequestPro("", "")
			.addRequestPro("", "")
			.addRequestPro("", "")
			.addRequestPro("", "");
		
		String url = "";
		ExaHttpDownUtil exaHttpDownUtil =new ExaHttpDownUtil(exaHttpDownConfig);
		exaHttpDownUtil.down(url);
		
	}

	private ExaHttpDownConfig exaHttpDownConfig;

	
	public ExaHttpDownUtil() {
	}

	public ExaHttpDownUtil(ExaHttpDownConfig exaHttpDownConfig) {
		this.exaHttpDownConfig = exaHttpDownConfig;
	}

	public void down(String url) {
		if (url == null || url.trim().equals("")) {
			return;
		}

		try {
			if (exaHttpDownConfig != null) {
				exaHttpDownConfig = new ExaHttpDownConfig();
			}

			// 设置代理
			Proxy proxy = null;
			if (exaHttpDownConfig.isProxy()) {
				String proxyHost = exaHttpDownConfig.getProxyIp();
				int proxyPort = exaHttpDownConfig.getProxyPort();
				InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(proxyHost, proxyPort);
				proxy = new Proxy(Type.HTTP, socketAddress);
			}

			URL u = new URL(url);
			HttpURLConnection httpConn = null;

			if (proxy != null) {
				httpConn = (HttpURLConnection) u.openConnection(proxy);
			} else {
				httpConn = (HttpURLConnection) u.openConnection();
			}
			httpConn.setReadTimeout(exaHttpDownConfig.getReadTimeout());
			httpConn.setConnectTimeout(exaHttpDownConfig.getConnectTimeout());
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setRequestMethod("GET");
			
			// 添加头属性，应对反爬虫技术
			// httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0;
			// Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84
			// Safari/537.36");
			Map<String, String> prosMap = exaHttpDownConfig.getRequestPros();
			for (Entry<String, String> entry : prosMap.entrySet()) {
				httpConn.setRequestProperty(entry.getKey(), entry.getValue());
				;
			}

			int code = httpConn.getResponseCode();
			// int len = httpConn.getContentLength();
			String encoding = httpConn.getContentEncoding();
			System.out.println(encoding);
			// 是否为断点下载，根据需要处理是否下载还是返回报文
			if (code == HttpURLConnection.HTTP_OK && code == HttpURLConnection.HTTP_PARTIAL) {

				InputStream inputStream = httpConn.getInputStream();
				// GZIPInputStream gZIPInputStream = new
				// GZIPInputStream(inputStream);//如果是gzip压缩格式传输，进行解压缩

				byte[] b = new byte[1024];
				int n = -1;
				StringBuffer sb = new StringBuffer();
				int count = 0;
				while ((n = inputStream.read(b)) != -1) {
					String str = new String(b, 0, n);
					System.out.println("读取长度：" + n);
					sb.append(str);
					count += n;
				}
				System.out.println("总长度：" + count);

				inputStream.close();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public ExaHttpDownConfig getExaHttpDownConfig() {
		return exaHttpDownConfig;
	}

	public void setExaHttpDownConfig(ExaHttpDownConfig exaHttpDownConfig) {
		this.exaHttpDownConfig = exaHttpDownConfig;
	}
}
